package com.lxk.service.event.handler;

import com.google.common.eventbus.SubscriberExceptionContext;
import com.google.common.eventbus.SubscriberExceptionHandler;
import com.lxk.common.EventTypeEnum;
import com.lxk.common.GsonUtils;
import com.lxk.service.component.RedisClient;
import com.lxk.service.event.domain.BaseEvent;
import com.lxk.service.event.domain.EventDto;
import com.lxk.service.event.domain.EventHandleMethodUnit;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;

import static com.lxk.common.Constant.RedisConstants.EVENT_QUEUE;

/**
 * Created by Lxk on 2020/7/25.
 */
@Slf4j
public class ExceptionHandler implements SubscriberExceptionHandler {

    /**
     * 处理异常的任务信息推送到redis队列中，等待小重试
     * @param throwable
     * @param subscriberExceptionContext
     */
    @Override
    public void handleException(Throwable throwable, SubscriberExceptionContext subscriberExceptionContext) {
        EventHandleMethodUnit unit = new EventHandleMethodUnit();
        unit.setEventContext(GsonUtils.getGson().toJson(subscriberExceptionContext.getEvent()));
        String beanName = getBeanName(subscriberExceptionContext.getSubscriber().getClass().getSimpleName());
        unit.setBeanName(beanName);
        unit.setMethodName(subscriberExceptionContext.getSubscriberMethod().getName());
        String eventContext = GsonUtils.getGson().toJson(unit);
        long res = RedisClient.getJedisClient().rpush(EVENT_QUEUE,eventContext);
        log.info("处理异常事件推送到事件补偿队列,eventContext:{},res:{}",eventContext,res);
    }

    private String getBeanName(String simpleName) {
        StringBuffer sb = new StringBuffer();
        sb.append(Character.toLowerCase(simpleName.charAt(0))).append(simpleName.substring(1));
        return sb.toString();
    }


    public static void main(String[] args) {
        EventHandleMethodUnit unit = new EventHandleMethodUnit();
        unit.setBeanName("blogPubEventHandler");
        unit.setMethodName("dispatchEvent");
        EventDto eventDto = new EventDto();
        eventDto.setContent("{\"dbId\":52,\"title\":\"test\",\"yn\":1,\"content\":\"test\"}");
        eventDto.setEventType(EventTypeEnum.EVENT_BLOG_PUBLISH);
        unit.setEventContext(GsonUtils.getGson().toJson(eventDto));
        System.out.println(GsonUtils.getGson().toJson(unit));
    }
}
